package com.example.weatheringwithyou.ui.me

import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.Toast
import androidx.lifecycle.lifecycleScope
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.example.weatheringwithyou.ChangeAvatarActivity
import com.example.weatheringwithyou.R
import com.example.weatheringwithyou.WeatherApplication
import com.example.weatheringwithyou.base.BaseBindingFragment
import com.example.weatheringwithyou.databinding.FragmentMeBinding
import com.example.weatheringwithyou.storage.TokenPreferences
import com.example.weatheringwithyou.ui.login.LoginActivity
import com.example.weatheringwithyou.utils.RetrofitClient
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class MeFragment : BaseBindingFragment<FragmentMeBinding>() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        //getUserInfo()
    }

    override fun onResume() {
        super.onResume()
        getUserInfo()
    }

    private fun getUserInfo() {
        lifecycleScope.launch(Dispatchers.Main) {
            val res = withContext(Dispatchers.IO) {
                RetrofitClient.apiService.getUserInfoApi()
            }
            // 检查响应码是否为10000（表示成功）
            if (res.code == 10000) {
                Toast.makeText(requireContext(), "获取用户信息成功", Toast.LENGTH_SHORT).show()
                val userData = res.data
                binding.tvAccount.text = userData?.username
                binding.tvGender.text = userData?.gender
                binding.tvNickname.text = userData?.nick_name
                binding.tvSignature.text = userData?.motto
                loadAvatar(userData?.avatar ?: "")

                if (userData != null) {
                    WeatherApplication.getInstance()?.initUser(userData)
                }
            } else {
                Toast.makeText(requireContext(), "获取用户信息失败", Toast.LENGTH_SHORT).show()
            }
        }
    }

    private fun loadAvatar(url: String) {
        lifecycleScope.launch {
            Glide.with(this@MeFragment)
                .load(url)
                .apply(
                    RequestOptions()
                        .circleCrop()
                        .placeholder(R.mipmap.avatar1)
                        .error(R.mipmap.avatar1)
                )
                .into(binding.ivAvatar)
        }
    }


    override fun initBinding(
        inflater: LayoutInflater,
        parent: ViewGroup?
    ): FragmentMeBinding {
        return FragmentMeBinding.inflate(inflater, parent, false)
    }

    override fun initView() {
        binding.ivAvatar.setOnClickListener { goToChangeAvatarActivity() }
        binding.ivEditAvatar.setOnClickListener { goToChangeAvatarActivity() }

        // 退出登录
        binding.btnLogout.setOnClickListener {
            // 清空token
            TokenPreferences.getInstance(requireContext()).clearToken()
            // 跳转到登录页面
            val intent = Intent(requireContext(), LoginActivity::class.java)
            startActivity(intent)
        }
    }

    fun goToChangeAvatarActivity() {
        var intent = Intent(context, ChangeAvatarActivity::class.java)
        startActivity(intent)
    }
}
